#import "UmengVertifyPlugin.h"
#if __has_include(<umeng_vertify/umeng_vertify-Swift.h>)
#import <umeng_vertify/umeng_vertify-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "umeng_vertify-Swift.h"
#endif

#define UMVerifySecret @"3jE+ZHm6q4mDTUqQOik3TVgxo0tgR6S3ZD+Gcw9fIIfPZPp1R2MAgGiVBv1HYLKMg9xbS2UGWPB/xLxyRmbJdfDmpindbw9ikooPggcZ3g11DmwYRxkZI5QzW+jUKcOb+0TJsZ5t5M+u88r9z6Pxo+g2P8qCql7aFMRLud48qlh0WJNUB45NxCdAFrE5qswiSZfz0ZnfgnsY6wMCfQNFQ8fSsLfYfiOZKJBxEQYGINqjwqohpjH7+Eyy/nVl3yl9/yGiKLHdUSY="

#import "UMVerifyHandler.h"
#import <UMVerify/UMVerify.h>
#import "ProgressHUD.h"
#import "Methods.h"

@interface UmengVertifyPlugin()<FlutterStreamHandler>

@property (nonatomic, strong) FlutterMethodChannel *methodChannel;
@property (nonatomic, strong) UMVerifyHandler* vfhandler;

@property (nonatomic, copy) FlutterEventSink eventSink;
@property (nonatomic, assign) BOOL isAgreeRule;
//@property (nonatomic, assign) BOOL isShowCloseButton;

@end


@implementation UmengVertifyPlugin

+ (instancetype)sharedInstance {
    static UmengVertifyPlugin *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
//        instance.isShowCloseButton = NO;
    });
    return instance;
}

- (UMVerifyHandler *)vfhandler{
    if (!_vfhandler) {
        _vfhandler = [[UMVerifyHandler alloc] init];
    }
    return _vfhandler;
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    
//  [SwiftUmengVertifyPlugin registerWithRegistrar:registrar];
    
    FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:@"umeng_vertify" binaryMessenger:[registrar messenger]];
    
    UmengVertifyPlugin *vertifyPlugin = [UmengVertifyPlugin sharedInstance];
    vertifyPlugin.methodChannel = methodChannel;
    
    [registrar addMethodCallDelegate:vertifyPlugin channel:methodChannel];
    
    FlutterEventChannel *echannel = [FlutterEventChannel eventChannelWithName:@"umeng_vertify_event" binaryMessenger:[registrar messenger]];
    [echannel setStreamHandler:vertifyPlugin];

}

#pragma mark -- FlutterEventChannel代理

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
    
    self.eventSink = events;
    
    return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
    
    self.eventSink = nil;
    
    return nil;
}


- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    [self methodCheckWithCall:call result:result];
}

- (bool)methodCheckWithCall:(FlutterMethodCall *)call result:(FlutterResult)result{
        
    __weak typeof(self) weakSelf = self;
    
    if ([call.method isEqualToString:initHelper]) {
        [self.vfhandler initUMCommon];
//        result(@"");

    }else if([call.method isEqualToString:setAuthSDKInfo]){
        [self.vfhandler setVerifySDKInfoWithSecret:UMVerifySecret complete:^(NSDictionary * _Nonnull resultDic) {
//            result(@"");
        }];
    }else if([call.method isEqualToString:checkEnvAvailable]){
        [self.vfhandler checkEnvAvailableWithType:(UMPNSAuthType) call.arguments[@"type"] complete:^(NSDictionary * _Nonnull resultDic) {
            if (weakSelf.eventSink) {
                NSDictionary *result = [self getresultDicFromDictionary:resultDic code:1 mesg:@"检测一键登录是否可用"];
                NSLog(@"检测一键登录是否可用de回调：%@",result);

                weakSelf.eventSink(result);
            }
        }];
    }else if([call.method isEqualToString:getLoginToken]){
        [self.vfhandler getLoginTokenWithTimeoutWithTimeOut:[call.arguments[@"timeOut"] doubleValue] complete:^(NSDictionary * _Nonnull resultDic) {
            NSString*code =[resultDic objectForKey:@"resultCode"];

            if([PNSCodeLoginControllerClickLoginBtn isEqualToString:code]){
                if([[resultDic objectForKey:@"isChecked"] boolValue]== YES){
                    [UMCommonHandler hideLoginLoading];//关闭默认loading
                    [ProgressHUD show];//显示loading
                }else{
                    [ProgressHUD showMessage:@"请勾选协议"];
                }

            }else if ([PNSCodeSuccess isEqualToString:code]){
                //点击登录按钮获取登录Token成功回调
                if (weakSelf.eventSink) {
                    NSDictionary *result = [weakSelf getresultDicFromDictionary:resultDic code:1 mesg:@"获取token"];
                    weakSelf.eventSink(result);
                }
//                NSString*token =[resultDic objectForKey:@"token"];
            }else if([PNSCodeLoginControllerClickChangeBtn isEqualToString:code]){
                //随便逛逛
                //显示关闭按钮
//                [UmengVertifyPlugin sharedInstance].isShowCloseButton = YES;
                [[UmengVertifyPlugin sharedInstance] setCloseButtonShow];
                [[UmengVertifyPlugin sharedInstance].methodChannel invokeMethod:@"touristsBrowse" arguments:@""];
                [UmengVertifyPlugin sharedInstance].isAgreeRule = NO;
                [UMVerifyHandler cancelLoginVC];

            }else if([PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:code]){
                [UmengVertifyPlugin sharedInstance].isAgreeRule = [[resultDic objectForKey:@"isChecked"] boolValue];
            }else {
                if ([PNSCodeCarrierChanged isEqualToString:code]||[PNSCodeUnknownOperator isEqualToString:code]||[PNSCodeNoCellularNetwork isEqualToString:code]) {
                    if (weakSelf.eventSink) {
                        NSString *result = [weakSelf getresultDic:resultDic];
                        NSDictionary *dic = @{
                            @"errorCode":@(-1),
                            @"errorMessage":result
                        };
                        weakSelf.eventSink(dic);
                    }
                }
            }
//            result(resultDic);
        }];
        
    }else if([call.method isEqualToString:quitLoginPage]){
        [UmengVertifyPlugin sharedInstance].isAgreeRule = NO;
        [UMVerifyHandler cancelLoginVC];
    }else if([call.method isEqualToString:loginField]){
        //自定义登录失败,关闭loading
        [ProgressHUD dismiss];
    }else if ([call.method isEqualToString:hideLoginLoading]){
        [ProgressHUD dismiss];
    }else if ([call.method isEqualToString:showLoading]){
        [ProgressHUD show];
    }
    
    result(@"");
    return false;
}


+ (void)clickOtherLogin:(OtherLogin)type {
    NSLog(@"点其他登录");
    switch (type) {
        case ClosePage:{
            [[UmengVertifyPlugin sharedInstance].methodChannel invokeMethod:@"touristsBrowse" arguments:@""];
            [UmengVertifyPlugin sharedInstance].isAgreeRule = NO;
            [UMVerifyHandler cancelLoginVC];
        }
            break;
        case PhoneNumber:{
            [UmengVertifyPlugin sharedInstance].isAgreeRule = NO;
            [UMVerifyHandler cancelLoginVC];
        }
            break;
        case Apple:{
            if (![UmengVertifyPlugin sharedInstance].isAgreeRule) {
                [ProgressHUD showMessage:@"请勾选协议"];
                return;
            }
            [ProgressHUD show];
            //发送apple登录消息
            [[UmengVertifyPlugin sharedInstance].methodChannel invokeMethod:@"appleLogin" arguments:@""];
        }
            break;
        case Wechat:{
            if (![UmengVertifyPlugin sharedInstance].isAgreeRule) {
                [ProgressHUD showMessage:@"请勾选协议"];
                return;
            }
            
//            [ProgressHUD show];
            //发送微信登录消息
            [[UmengVertifyPlugin sharedInstance].methodChannel invokeMethod:@"wechatLogin" arguments:@""];
        }
            break;
        default:
            break;
    }
}

+ (void)setCloseShow {
    [[UmengVertifyPlugin sharedInstance] setCloseButtonShow];
}

+ (void)setCloseHide {
    [[UmengVertifyPlugin sharedInstance] setCloseButtonHide];
}

//设置关闭按钮显示
- (void)setCloseButtonShow{
    NSLog(@"设置关闭按钮显示");
    [[NSUserDefaults standardUserDefaults] setObject:showCloseButton forKey:closeUserDefault];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [UMVerifyHandler changeBtnShowWithHidden:YES title:@""];
}

//设置关闭按钮隐藏
- (void)setCloseButtonHide{
    NSLog(@"设置关闭按钮隐藏");
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:closeUserDefault];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [UMVerifyHandler changeBtnShowWithHidden:NO title:@"随便逛逛"];
}


//获取关闭按钮状态
+ (BOOL)getCloseButtonIsShow{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    if ([[userDefaults objectForKey:closeUserDefault] isEqualToString:showCloseButton]
//        && [UmengVertifyPlugin sharedInstance].isShowCloseButton
        ) {
        return YES;
    }else{
        return NO;
    }
}

+ (NSString *)getSlognName{
    return [UMCommonUtils getCurrentCarrierName];
}

- (NSDictionary *)getresultDicFromDictionary:(NSDictionary *)dic code:(int)code mesg:(NSString *)mesg{
    
    NSDictionary *resultDic = @{};
    
    NSError *error;
    NSData *data = [NSData data];
    if (dic) {
        data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    }
    NSString *jsonString = @"";
    if (data) {
        jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
//    [NSString stringWithFormat:@"%d",type]
    if (dic) {
        resultDic = @{@"errorCode":@(code),
                      @"errorMessage":mesg,
                      @"uMTokenData":jsonString};
    }
    
    return resultDic;
}

- (NSString *)getresultDic:(NSDictionary *)dic{
    
    
    NSError *error;
    NSData *data = [NSData data];
    if (dic) {
        data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    }
    NSString *jsonString = @"";
    if (data) {
        jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
//    [NSString stringWithFormat:@"%d",type]
    
    
    return jsonString;
}

@end
